$(function () {
    $("#li-nav-subscribe").addClass("active");

    subscribeHandle.stadiumTypeTabClick(true)
})

//预约协调
var subscribeHandle = {
    initCalendar: function () {
        $("#calendar").calendar({
            cache: false,
            dateChanged: subscribeHandle.refreshDate
        });
    },
    refreshStadiumType: function (option) {
        userData.tid = option.tid
        userDisplayData.type = option.displayName

        stadiumList.initCallback()
        subscribe.getStadiumByType()
    },
    refreshDate: function (date) {
        var nextMonth = Date.parse(date);
        nextMonth.setMonth(nextMonth.getMonth() + 1);

        userData.date = date
        userData.endDate = nextMonth.format("yyyy-MM-dd")
        userDisplayData.date = date
        userDisplayData.endDate = nextMonth.format("yyyy-MM-dd")
        subscribe.getTimeSpansByDate(date)
    },
    refreshEndDate: function (date) {
        var date = Date.parse(date);
        userData.endDate = date.format("yyyy-MM-dd")
        userDisplayData.endDate = date.format("yyyy-MM-dd")

        orderReportForms.refresh()
    },
    refreshSid: function (option) {
        userData.sid = option.sid
        userDisplayData.name = option.name

        timeSpansList.initCallback()
        confirmSubscribeCallback.initCallback()

        subscribeHandle.initCalendar()
        subscribeFlow.flowA()
    },
    returnClick: function () {
        subscribeFlow.flowA()
        $(document).trigger(modalHandle.hideEvent)
    },
    plainSubscribeClick: function () {
        userData.timeSpans = timeSpansList.getActiveTimeSpans()
        userDisplayData.timeSpans = timeSpansList.getActiveTimeSpanDisplays()
        userData.isRandom = timeSpansList.getIsRandom()

        if (userData.timeSpans == 0) {
            alert('请选择预约时间段');
        } else {
            userData.timeSpans = arrayToJson(timeSpansList.getActiveTimeSpans())

            orderReportForms.refresh()

            subscribeFlow.confirmFlowA1()

        }
    },
    cycleSubscribeClick: function () {
        userData.timeSpans = timeSpansList.getActiveTimeSpans()
        userDisplayData.timeSpans = timeSpansList.getActiveTimeSpanDisplays()
        userData.isRandom = timeSpansList.getIsRandom()

        if (userData.timeSpans == 0) {
            alert('请选择预约时间段');
        } else {
            userData.timeSpans = arrayToJson(timeSpansList.getActiveTimeSpans())

            orderReportForms.initCalendarA()
            orderReportForms.refresh()

            subscribeFlow.confirmFlowA2()
        }
    },
    stadiumTypeTabClick: function (isTrigger) {
        var $li = $("#stadiumTab li");
        $li.unbind('click')
        $li.on('click', function () {
            var tid = $(this).attr('value');
            var displayName = $(this).find('b').html()

            subscribeHandle.refreshStadiumType({tid: tid, displayName: displayName})

            modalHandle.initEvent()
        });

        if (isTrigger) {
            $li.eq(0).click();
        }
    },
    stadiumSubscribeClick: function () {
        var $a = $("a[type='beforeSubscribe']");
        $a.unbind('click')
        $a.bind('click', function () {
            if (!checkLogin(url.getSubscribeIndex)) {
                $("#modal-subscribe-login-navigation").modal('show');
            } else {
                var sid = $(this).parents("div.thumbnail").attr('sid')
                var name = $(this).parents("div.thumbnail").find('p:eq(1)').html()

                subscribeHandle.refreshSid({sid: sid, name: name})
            }
        })
    },
    confirmPlainSubscribeClick: function () {
        subscribe.confirmSubscribe(0)
    },
    confirmCycle1SubscribeClick: function () {
        subscribe.confirmSubscribe(1)
    },
    confirmPlain2SubscribeClick: function () {
        subscribe.confirmSubscribe(2)
    },
    confirmPlain3SubscribeClick: function () {
        subscribe.confirmSubscribe(3)
    }
}

//确认预约后的回调
var confirmSubscribeCallback = {
    initCallback: function () {
        $(document).unbind(callback.confirmSubscribeBeforeCallback)
        $(document).bind(callback.confirmSubscribeBeforeCallback, function () {
            subscribeFlow.flowC()
        })
        $(document).unbind(callback.confirmSubscribeSuccessCallback)
        $(document).bind(callback.confirmSubscribeSuccessCallback, function (data) {
            confirmSubscribeCallback.successCallback(data)
        })
        $(document).unbind(callback.confirmSubscribeErrorCallback)
        $(document).bind(callback.confirmSubscribeErrorCallback, function (data) {
            confirmSubscribeCallback.errorCallback(data)
        })
    },
    successCallback: function (data) {
        if (!data.json.success) {
            if (data.json.dataType == 'timeSpans') {
                var array = JSON.parse(data.json.data)
                var timeSpan = $("code[type='occupiedError']")
                var timeSpanList = $("#div-timeSpanOccupied")
                timeSpanList.empty()
                $(array).each(function (i) {
                    timeSpan.find("span").html(array[i].name + "<br>" + array[i].value)

                    timeSpanList.append(timeSpan.html())
                })

                modalHandle.showErrorOccupied()
                modalHandle.hideError500()
            } else {
                var otherErrorList = $("#div-otherError")
                otherErrorList.empty();
                otherErrorList.append("<span class='label label-danger'>" + data.json.exception + "</span>")

                modalHandle.showError500()
                modalHandle.hideErrorOccupied()
            }

            subscribeFlow.flowE()
        } else {
            subscribeFlow.flowD()
        }
    },
    errorCallback: function (data) {
        if (data.xhr.status == 405) {
            modalHandle.hide()
            $("#modal-subscribe-login-navigation").modal('show')
        } else {
            var otherError = $("code[type='otherError']")
            var otherErrorList = $("#div-otherError")
            otherErrorList.empty();
            otherErrorList.append(otherError.html())

            modalHandle.showError500()
            modalHandle.hideErrorOccupied()

            subscribeFlow.flowE()
        }
    }
}

//预约流程modal管理
var modalHandle = {
    $modal: $('#modal-subscribe-flow'),
    hideEvent: $.Event("subscribe.modal.hide", this),
    initEvent: function () {
        modalHandle.$modal.unbind('hide.bs.modal')
        modalHandle.$modal.on('hide.bs.modal', function () {
            $(document).trigger(modalHandle.hideEvent)
        })
    },
    $title: function () {
        return modalHandle.$modal.find('.modal-title')
    },
    $body: function () {
        return modalHandle.$modal.find('.modal-body')
    },
    $footer: function () {
        return modalHandle.$modal.find('.modal-footer')
    },
    $btn1: function () {
        return modalHandle.$footer().find('button:eq(0)')
    },
    $btn2: function () {
        return modalHandle.$footer().find('button:eq(1)')
    },
    $btn3: function () {
        return modalHandle.$footer().find('button:eq(2)')
    },
    $btn4: function () {
        return modalHandle.$footer().find('button:eq(3)')
    },
    show: function () {
        modalHandle.$modal.modal('show')
    },
    hide: function () {
        modalHandle.$modal.modal('hide')
    },
    showError500: function () {
        $("div.flowE .col-xs-8 .row:eq(2)").show()
        $("div.flowE .col-xs-8 .row:eq(3)").show()
    },
    hideError500: function () {
        $("div.flowE .col-xs-8 .row:eq(2)").hide()
        $("div.flowE .col-xs-8 .row:eq(3)").hide()
    },
    showErrorOccupied: function () {
        $("div.flowE .col-xs-8 .row:eq(0)").show()
        $("div.flowE .col-xs-8 .row:eq(1)").show()
    },
    hideErrorOccupied: function () {
        $("div.flowE .col-xs-8 .row:eq(0)").hide()
        $("div.flowE .col-xs-8 .row:eq(1)").hide()
    },
    hideEndDate: function () {
        modalHandle.$body().find("#div-end-date").hide()
    },
    showEndDate: function () {
        modalHandle.$body().find("#div-end-date").show()
    },
    hideBtn1: function () {
        modalHandle.$btn1().hide()
    },
    showBtn1: function () {
        modalHandle.$btn1().show()
    },
    hideBtn2: function () {
        modalHandle.$btn2().hide()
    },
    showBtn2: function () {
        modalHandle.$btn2().show()
    },
    hideBtn3: function () {
        modalHandle.$btn3().hide()
    },
    showBtn3: function () {
        modalHandle.$btn3().show()
    },
    hideBtn4: function () {
        modalHandle.$btn4().hide()
    },
    showBtn4: function () {
        modalHandle.$btn4().show()
    },
    hideChildren: function () {
        modalHandle.$body().children().hide()
    },
    initTitle: function (html) {
        modalHandle.$title().html(html)
    },
    initBtn1: function (html, fn) {
        modalHandle.$btn1().blur()
        modalHandle.$btn1().unbind('click')

        if (html != null) modalHandle.$btn1().html(html)
        if (fn != null) modalHandle.$btn1().on('click', fn)
    },
    initBtn2: function (html, fn) {
        modalHandle.$btn2().blur()
        modalHandle.$btn2().unbind('click')

        if (html != null) modalHandle.$btn2().html(html)
        if (fn != null) modalHandle.$btn2().on('click', fn)
    },
    initBtn3: function (html, fn) {
        modalHandle.$btn3().blur()
        modalHandle.$btn3().unbind('click')

        if (html != null) modalHandle.$btn3().html(html)
        if (fn != null) modalHandle.$btn3().on('click', fn)
    },
    initBtn4: function (fn) {
        modalHandle.$btn4().blur()
        modalHandle.$btn4().unbind('click')

        if (fn != null) modalHandle.$btn4().on('click', fn)
    }
}

//预约流程管理
var subscribeFlow = {
    //options.type 预约类型；1.普通预约；2.周期预约
    confirmFlowA1: function () {
        subscribeFlow.flowB();

        modalHandle.initTitle('确认您的预约')
        modalHandle.initBtn1('确认', subscribeHandle.confirmPlainSubscribeClick)
        modalHandle.initBtn4(subscribeHandle.returnClick)
        modalHandle.showBtn1()
        modalHandle.hideBtn2()
        modalHandle.hideBtn3()
        modalHandle.showBtn4()
        modalHandle.hideEndDate()
    },
    confirmFlowA2: function () {
        subscribeFlow.flowB();

        modalHandle.initTitle('确认您的预约')
        modalHandle.initBtn1('每天', subscribeHandle.confirmCycle1SubscribeClick)
        modalHandle.initBtn2('每星期', subscribeHandle.confirmPlain2SubscribeClick)
        modalHandle.initBtn3('每月', subscribeHandle.confirmPlain3SubscribeClick)
        modalHandle.initBtn4(subscribeHandle.returnClick)
        modalHandle.showBtn1()
        modalHandle.showBtn2()
        modalHandle.showBtn3()
        modalHandle.showBtn4()
        modalHandle.showEndDate()
    },
    flowA: function () {
        modalHandle.initTitle('选择日期和时间段')
        modalHandle.initBtn1('普通预约', subscribeHandle.plainSubscribeClick)
        modalHandle.initBtn2('周期预约', subscribeHandle.cycleSubscribeClick)
        modalHandle.showBtn1()
        modalHandle.showBtn2()
        modalHandle.hideBtn3()
        modalHandle.hideBtn4()

        modalHandle.show()

        modalHandle.hideChildren()
        $("#modal-subscribe-flow .flowA").show()
    },
    flowB: function () {
        modalHandle.show()

        modalHandle.hideChildren()
        $("#modal-subscribe-flow .flowB").show()
    },
    flowC: function () {
        modalHandle.initTitle('稍等片刻')
        modalHandle.hideBtn1()
        modalHandle.hideBtn2()
        modalHandle.hideBtn3()
        modalHandle.hideBtn4()

        modalHandle.show()

        modalHandle.hideChildren()
        $("#modal-subscribe-flow .flowC").show()
    },
    flowD: function () {
        modalHandle.initTitle('成功')
        //modalHandle.showBtn4()
        modalHandle.hideBtn1()
        modalHandle.hideBtn2()
        modalHandle.hideBtn3()
        modalHandle.hideBtn4()

        modalHandle.show()

        modalHandle.hideChildren()
        $("#modal-subscribe-flow .flowD").show()
    },
    flowE: function () {
        modalHandle.initTitle('失败')
        modalHandle.showBtn4()
        modalHandle.hideBtn1()
        modalHandle.hideBtn2()
        modalHandle.hideBtn3()

        modalHandle.show()

        modalHandle.hideChildren()
        $("#modal-subscribe-flow .flowE").show()
    }
}

//场馆html样式管理
var stadiumStyle = {
    //设置场馆的padding
    setStadiumHtmlPadding: function () {
        var thumbnailPanels = $(".yois-subscribe-stadium .list .col-xs-4");
        var j = 0;
        thumbnailPanels.each(function (i) {
            if (i == j) {
                $(thumbnailPanels[i]).addClass("yois-left-element");
                $(thumbnailPanels[i + 1]).addClass("yois-center-element");
                $(thumbnailPanels[i + 2]).addClass("yois-right-element");
                j = j + 3;
            }
        })
    },
    //设置场馆缩略图的高度
    setStadiumThumbnail: function () {
        var imgs = $(".thumbnail img");
        imgs.each(function (i) {
            var img = $(this);
            var imgWidth = img.innerWidth();
            var imgHeight = 9 * imgWidth / 16;
            img.css("height", imgHeight);
        })
    }
}

//时间段列表管理
var timeSpansList = {
    $list: function () {
        return $(".yois-subscription-condition .btn-group-stadium-time");
    },
    $actives: function () {
        return timeSpansList.$list().find('label.active')
    },
    getIsRandom: function () {
        var result = $("#checkbox-random")[0].checked
        return result
    },
    getActiveTimeSpans: function () {
        var timeSpansArray = []

        timeSpansList.$actives().each(function (i) {
            if (i == 0) timeSpansArray[0] = 'string'
            timeSpansArray[i + 1] = $(this).html()
        })

        return timeSpansArray;
    },
    getActiveTimeSpanDisplays: function () {
        var timeSpansArray = []

        timeSpansList.$actives().each(function (i) {
            timeSpansArray[i] = $(this).html()
        })

        return timeSpansArray;
    },
    initCallback: function () {
        $(document).unbind(callback.getTimeSpansByDateSuccessCallback)
        $(document).on(callback.getTimeSpansByDateSuccessCallback, function (data) {
            var list = timeSpansList.$list();
            list.empty();

            var timeSpan = $("code[type='timeSpan']")
            $(data.json).each(function (i) {
                timeSpan.find('label').html(data.json[i].value)

                list.append(timeSpan.html())
            });
            if (data.json.length == 0) {
                var info = $("code[type='timeSpanEmptyInfo']")
                list.append(info.html())
            }
        })

        $(document).unbind(callback.getTimeSpansByDateCompleteCallback)
        $(document).on(callback.getTimeSpansByDateCompleteCallback, function (data) {
            $("#modal-content-loadingA").fadeOut(600);
        })

        $(document).unbind(callback.getTimeSpansByDateBeforeCallback)
        $(document).on(callback.getTimeSpansByDateBeforeCallback, function (data) {
            $("#modal-content-loadingA").fadeIn(10);
        })
    }
}

//预约报表
var orderReportForms = {
    initCalendarA: function () {
        var html = "<a href=\"javascript:void(0)\" data-html=\"true\" data-placement=\"right\" data-container=\"body\" data-toggle=\"popover\" data-content=\"<div class='calendar' style='margin-bottom: 10px; height: 250px;'><div id='calendarA' class='day'><div class='DaySelect'><div data-tag='year'></div><div data-tag='month' style='margin-right: 5px'></div><div class='btn btn-default' data-tag='nextMonth' style='margin-right: 5px;'><i class='glyphicon glyphicon-chevron-right'></i> 下个月</div><div class='btn btn-default' data-tag='today'> 今天</div></div><div class='allDay'></div></div></div>\" role=\"button\" class=\"btn btn-success btn-block\" id=\"btn-subscribeEndDate\">更换截至日期</a>"
        $("#div-subscribeEndDate").html(html)

        $("#btn-subscribeEndDate").popover()

        $("#btn-subscribeEndDate").unbind('shown.bs.popover')
        $("#btn-subscribeEndDate").on('shown.bs.popover', function () {
            var nextMonth = Date.parse(userData.date);
            nextMonth.setDate(nextMonth.getDate() + 1)
            $("#calendarA").calendar({
                year: nextMonth.getFullYear(),
                month: nextMonth.getMonth(),
                day: nextMonth.getDate(),
                cache: false,
                dateChanged: subscribeHandle.refreshEndDate
            });
        })

        $("#btn-subscribeEndDate").unbind('subscribe.modal.hide')
        $(document).on('subscribe.modal.hide', function () {
            $("#btn-subscribeEndDate").popover('hide')
        })
    },
    refresh: function () {
        $("#span-stadiumType").html(userDisplayData.type)
        $("#span-stadiumName").html(userDisplayData.name)
        $("#span-subscribeStartDate").html(userDisplayData.date)
        $("#span-subscribeEndDate").html(userDisplayData.endDate)

        var timeSpanHtml = $("code[type='reportFormTimeSpan']")

        $("#div-timeSpans").empty()
        $(userDisplayData.timeSpans).each(function (i) {
            timeSpanHtml.find('span').html(userDisplayData.timeSpans[i])

            $("#div-timeSpans").append(timeSpanHtml.html())
        })
    }
}

//场馆列表管理
var stadiumList = {
    $list: function () {
        return $(".yois-subscribe-stadium .list")
    },
    initCallback: function () {
        $(document).unbind(callback.getStadiumByTypeSuccessCallback)
        $(document).on(callback.getStadiumByTypeSuccessCallback, function (data) {
            var list = stadiumList.$list()
            list.empty()

            var stadium = $("code[type='stadium']")
            var thumbnail = stadium.find('div.thumbnail')
            var a = thumbnail.find('img').parent()
            var img = thumbnail.find('img')
            var p1 = thumbnail.find('p:eq(0)')
            var p2 = thumbnail.find('p:eq(1)')
            $(data.json).each(function (i) {
                var jsons = data.json;
                var stateId = jsons[i].stadiumStateId;
                if (stateId == 2 || stateId == 3) {
                    thumbnail.find("a[name='startSub']").attr("class", "btn btn-danger disabled")
                } else if (stateId == 1) {
                    thumbnail.find("a[name='startSub']").attr("class", "btn btn-danger")
                }
                thumbnail.attr('sid', this.stadiumId)
                a.attr('href', url.detailedUrl + "?sid=" + this.stadiumId)
                img.attr('src', yomUrl + this.stadiumImg)
                p1.html(this.stadiumGroupDomain.stadiumGroupName);
                p2.html(this.stadiumName);
                list.append(stadium.html())

            });

            stadiumStyle.setStadiumHtmlPadding();
            stadiumStyle.setStadiumThumbnail();

            subscribeHandle.stadiumSubscribeClick();
        })

        $(document).unbind(callback.getStadiumByTypeCompleteCallback)
        $(document).on(callback.getStadiumByTypeCompleteCallback, function (data) {
            $("#modal-loadingA").fadeOut(600);
        })

        $(document).unbind(callback.getStadiumByTypeBeforeSendCallback)
        $(document).on(callback.getStadiumByTypeBeforeSendCallback, function (data) {
            $("#modal-loadingA").fadeIn(10);
        })
    }
}